package com.bestv.search.engine.compass.extend;

import com.bestv.search.common.util.StringConst;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.search.HitCollector;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Justin Luo
 */

// $Id$
public class GroupCollector extends HitCollector {

    private final Log log = LogFactory.getLog(GroupCollector.class);
    private Map<String, Integer> groups = new HashMap<String, Integer>();
    private String[] fields;

    public GroupCollector(String[] fields) {
        this.fields = fields;
    }

    @Override
    public void collect(int doc, float score) {
        if (score > 0.0f) {
            if (fields == null) {
                log.error("Fileds list is null, please init it first ");
            } else {
                String key = StringConst.EMPTY;
                try {
                    key = fields[doc];
                } catch (ArrayIndexOutOfBoundsException e) {
                    // ignore this exception
                    return;
                }
                Integer count = groups.get(key);
                if (count == null) {
                    groups.put(key, 1);
                } else {
                    groups.put(key, count + 1);
                }
            }
        }
    }

    public Map<String, Integer> getGroups() {
        return groups;
    }
}
